#include "mainapp.h"
#include "ui_mainapp.h"
#include <QTextStream>
#include <QPushButton>
#include "TimeWidget.h"
#include "Constant.h"
#include "TimeEntity.h"
#include "SqliteDao.h"

MainApp *MainApp::mainApp = NULL;
MainApp::MainApp(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainApp)
{
//    Constant::initData();
    MainApp::mainApp = this;
    ui->setupUi(this);
    //应用样式 apply the qss style
    QFile file(":/qss/base.css");
    file.open(QFile::ReadOnly);
    QTextStream stream(&file);
    QString stylesheet = stream.readAll();
    this->setStyleSheet(stylesheet);
    file.close();

    ui->boxAdd->setVisible(false);

    loadTimeList();
}


MainApp::~MainApp()
{
    delete ui;
}
void MainApp::timeDataEdit(TimeWidget *tw){
    editTimeWidget = tw;
    TimeEntity data = tw->timeData;
    ui->txtTitle->setPlainText(data.title);
    ui->numHour->setValue(data.hour);
    ui->numMinute->setValue(data.minute);
    ui->numSecond->setValue(data.second);
    ui->numRefresh->setValue(data.refreshTime);
    ui->boxAdd->setVisible(true);
}
void MainApp::on_btnAdd_clicked()
{
    if(ui->boxAdd->isVisible()){
        ui->boxAdd->setVisible(false);
    }else{
        ui->boxAdd->setVisible(true);
    }

}
void MainApp::loadTimeList(){
//    Constant::objList.append(tw);
    QList<TimeEntity> *tList = SqliteDao::instance()->sqlQuery();
    TimeEntity data;
    for(int i=0;i<tList->size();i++){
        data = tList->at(i);
//        data.toString();
        addTime(&data);
    }

}
void MainApp::on_btnOk_clicked()
{
    //传递参数
    TimeEntity timeData;
    timeData.title = ui->txtTitle->toPlainText();
    timeData.hour = ui->numHour->value();
    timeData.minute = ui->numMinute->value();
    timeData.second = ui->numSecond->value();
    timeData.refreshTime = ui->numRefresh->value();

    ui->boxAdd->setVisible(false);
    if(isEdit){
        editTimeWidget->init(timeData);
        isEdit = false;
    }else{
        addTime(&timeData);
        SqliteDao::instance()->sqlInsert(&timeData);
    }
}
void MainApp::addTime(TimeEntity *timeData){
    //添加倒计时
    //wnum 每行能放的数量
    int w,h,h2,
        wnum = Constant::WW/Constant::TW,
        num = Constant::objList.length();
    w = (num % wnum) * Constant::TW;
    h = num / wnum * Constant::TH;
    h2 = h + Constant::TH;
    ui->scrollAreaWidgetContents->setGeometry(0,0,Constant::WW,h2);
    if(w > Constant::WW)w = 0;
    QWidget *area = ui->scrollAreaWidgetContents;
    TimeWidget *tw = new TimeWidget(area);
    tw->setGeometry(w,h,Constant::TW,Constant::TH);
    tw->setVisible(true);//没有这句不显示？！
    Constant::objList.append(tw);
    tw->init(*timeData);
}

void MainApp::on_btnCancel_clicked()
{
    ui->numHour->setValue(0);
    ui->numMinute->setValue(0);
    ui->numSecond->setValue(0);
    ui->txtTitle->setPlainText("");
    ui->boxAdd->setVisible(false);
    isEdit = false;
}
